import { _decorator, assert, AssetManager, assetManager, AudioClip, Component, Node, Prefab } from 'cc';

export class ResManager {
    private static _instance: ResManager = null!;
    /** 获取单例的接口 */
    static getInstance() {
        if (this._instance === null) {
            this._instance = new ResManager();
        }
        return this._instance;
    }

    private constructor() {
        // 私有化的构造函数
    }

    loadPrefab(bundleName: string, prefabPath: string, cb: (prefab: Prefab | null) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            bundle.load(prefabPath, Prefab, (err, prefab: Prefab) => {
                if (err) {
                    console.error(err);
                    cb(null);
                    return;
                }
                cb(prefab)
            })
        })
    }


    loadAudioClip(bundleName:string,audioPath:string,cb:(asset:AudioClip|null) => void){
        assetManager.loadBundle(bundleName,(e,bundle) =>{
            bundle.load(audioPath,AudioClip,(err,assert:AudioClip) =>{
                if(err){
                    console.error(err);
                    cb(null);
                    return;
                }
                cb(assert)

            })
        })
    }

    loadBundle(bundleName: string, cb?: (bundle: AssetManager.Bundle | null) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            cb && cb(bundle);
        });
    }


    loadBundleAsync(bundleName: string): Promise<AssetManager.Bundle> {
        return new Promise<AssetManager.Bundle>(rs => {
            this.loadBundle(bundleName, rs);
        })
    }

    loadPrefabByBUrl(bUrl: IBundleUrl, cb: (prefab: Prefab | null) => void) {
        this.loadPrefab(bUrl.b, bUrl.l, cb);
    }

    loadAudioByBUrl(bUrl: IBundleUrl, cb: (audioClip: AudioClip | null) => void) {
        this.loadAudioClip(bUrl.b, bUrl.l, cb);
    }

}


